package sparrow.ui;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;

import sparrow.common.TopicHistory;
import sparrow.ui.nox.SystemPath;



/*
 * Created on 2006-9-9
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
/**
 * @author shinysky
 */
class ChatPane extends JSplitPane implements ActionListener// ,MouseListener
{
	/**
	 * we don't know much about it
	 */
	private static final long serialVersionUID = -1915394855935441419L;

	public static final int WIDTH_DEFLT = 400;
	public static final int WIDTH_PREF = 400;
	public static final int WIDTH_MAX = 2000;
	public static final int WIDTH_MIN = 300;
	public static final int HEIGHT_DEFLT = 300;
	public static final int HEIGHT_PREF = 300;
	public static final int HEIGHT_MAX = 2000;
	public static final int HEIGHT_MIN = 200;

//	private JScrollPane sp_historymsg;
//	private JTextPane tp_historymsg;
	private ChatHistoryPane chatHistory;
	private JPanel p_inputpaneAndButtons;
	private JScrollPane sp_input;
	private JTextPane tp_input;
	private JPanel p_buttons;
	private JButton b_emotion;
//	private JButton b_nudge;
//	private static final String nudgeMsg = "[F:999]"; 
//
//	private JButton b_snapshot;
//	private JButton b_snapconfig;
//	JPopupMenu menuSnap;
//	JMenuItem doSnap;
	JCheckBoxMenuItem hideFrame;
	
	public static final DecimalFormat fmNum = new DecimalFormat("000");
	
	private JButton b_send;
	
	String historymsg_save;
	
	String currentmsg_save;
	
	
	private Format fmDate = new SimpleDateFormat("yyyy/MM/dd E HH:mm:ss");
	
	private static final String sayHello = "\t------====  Welcome to the Chat Room  ====------\n"
		+ "\t  ------====     What do U wanna say ?   ====------\n";

	private TopicHistory th;
	
	public ChatPane(TopicHistory th) {
		super(JSplitPane.VERTICAL_SPLIT);

		this.th = th;
		
		// strLength = sayHello.length();
		// position = 0;
		
		chatHistory = new ChatHistoryPane(th);
		historymsg_save = new String();
		historymsg_save += sayHello;

//		tp_historymsg.replaceSelection(sayHello);

		// tp_historymsg.setToolTipText("History Messages");
//		tp_historymsg.setBackground(new Color(180, 250, 250));
//		tp_historymsg.setSelectionColor(Color.YELLOW);
		
//		tp_historymsg.setEditable(false);
//		sp_historymsg = new JScrollPane(chatHistory);
//		sp_historymsg = new JScrollPane(chatHistory);
//		sp_historymsg.setAutoscrolls(true);

		p_inputpaneAndButtons = new JPanel();

		tp_input = new JTextPane();
		// tp_msg.setText(sayHello);
		tp_input
		.setToolTipText(getHtmlText("Input your message and press \"Send\" <br>or press Enter"));

		
		tp_input.addKeyListener(new KeyListener() {
			public void keyPressed(KeyEvent event) {
				int keyCode = event.getKeyCode();
				
				if (keyCode == KeyEvent.VK_ENTER) {
					System.out.println("You press the key : Enter");
					sendMessage();
				}
			}

			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
			}

			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
			}
		});
		sp_input = new JScrollPane(tp_input);

		p_buttons = new JPanel();

		Dimension buttonSize = new Dimension(26, 26);

		b_emotion = new JButton(new ImageIcon(SystemPath.ICONS_RESOURCE_PATH + "emotion.png"));
		b_emotion.setToolTipText(getHtmlText("Insert a emotion image"));
		b_emotion.setActionCommand("Emotion");
		b_emotion.addActionListener(this);
		// b_InsertImg.setContentAreaFilled(false);
		b_emotion.setSize(buttonSize);
		b_emotion.setPreferredSize(buttonSize);
		b_emotion.setMaximumSize(buttonSize);
		b_emotion.setMinimumSize(buttonSize);
				// b_send = new JButton("Send");
		b_send = new JButton(new ImageIcon(SystemPath.ICONS_RESOURCE_PATH + "send.png"));
		b_send.setMnemonic('S');
		// b_send.setPreferredSize(new Dimension(100,40));
		b_send.setActionCommand("Send");
		b_send.setToolTipText(getHtmlText("Send"));
		b_send.addActionListener(this);
		// b_send.setContentAreaFilled(false);
		b_send.setSize(buttonSize);
		b_send.setPreferredSize(buttonSize);
		b_send.setMaximumSize(buttonSize);
		b_send.setMinimumSize(buttonSize);

		p_buttons.setOpaque(false);
		p_buttons.setLayout(new BoxLayout(p_buttons, BoxLayout.X_AXIS));
		p_buttons.add(b_emotion);
		p_buttons.add(Box.createHorizontalGlue());
		p_buttons.add(b_send);
		// p_buttons.add(p_side, BorderLayout.CENTER);
		// p_buttons.add(b_send, BorderLayout.WEST);

		p_inputpaneAndButtons.setOpaque(false);
		// p_msgAndButtons.setBackground(Color.blue);
		p_inputpaneAndButtons.setLayout(new BorderLayout());
		p_inputpaneAndButtons.add(p_buttons, BorderLayout.NORTH);
		p_inputpaneAndButtons.add(sp_input, BorderLayout.CENTER);

		/*
		 * msgPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, sp_hmsg,
		 * p_msgAndButtons); msgPane.setOneTouchExpandable(true);
		 * msgPane.setOpaque(false);
		 */
		// msgPane.setContinuousLayout(true);
		this.setSize(new Dimension(WIDTH_DEFLT,
				HEIGHT_DEFLT - 35));
		this.setDividerLocation(0.65);// å¿…é¡»å…ˆæŒ‡å®šå°ºå¯¸æ‰�æœ‰æ•ˆ
		this.setResizeWeight(0.62d);
		this.setDividerSize(3);
		// this.setOneTouchExpandable(true);
//		this.add(sp_historymsg);
		this.add(chatHistory);
		this.add(p_inputpaneAndButtons);
		// this.setLayout(new BorderLayout());
		// this.add(msgPane, BorderLayout.CENTER);
		// this.setOpaque(false);//åœ¨å½“å‰�ä½¿ç”¨çš„èƒŒæ™¯ä¸‹, è®¾ä¸ºé€�æ˜Žä¼¼ä¹Žä¸�å¤ªå¥½çœ‹...
	}

	private String getHtmlText(String text) {
		return ("<html><BODY bgColor=#ffffff><Font color=black>" + text + "</Font></BODY></html>");
	}
	
	public void showMsgDialog(String msg) {
		JOptionPane.showMessageDialog((Component) null, msg,
				"Message form the Server", JOptionPane.INFORMATION_MESSAGE);
	}
/*
	public void showFailedSendingMsg(String msg){		
		tp_historymsg.setEditable(true);
		tp_historymsg.setCaretPosition(styledDoc.getLength());// !!!
		styledDoc.setLogicalStyle(tp_historymsg.getCaretPosition(), italic);
		tp_historymsg
				.replaceSelection("Sorry, failed to send out the msg:\n" + msg + '\n');
		tp_historymsg.setEditable(false);
	}
	
	public void showFeedbackMsg(String msg, String errorString){		
		tp_historymsg.setEditable(true);
		tp_historymsg.setCaretPosition(styledDoc.getLength());// !!!
		styledDoc.setLogicalStyle(tp_historymsg.getCaretPosition(), red);
		tp_historymsg
				.replaceSelection(errorString + "\n");
		tp_historymsg.setEditable(false);
	}
*/	
	/**
	 * 
	 * @param strs
	 *            1:sender;2:receiver;3:time;4:msg
	 * @param incomingPic
	 */	
	public void incomingMsgProcessor(String sender, String time,
			Object msgdata){
		if(msgdata instanceof String)
			incomingMsgProcessor(sender, time, (String)msgdata, null);
		else if(msgdata instanceof ImageIcon)
			incomingMsgProcessor(sender, time, null, (ImageIcon)msgdata);
	}
	
	public void incomingMsgProcessor(String sender, String time,
			final String strmsg, ImageIcon incomingPic) {
		System.out.println("playAudio()...");
		Thread playThd = new Thread(new Runnable() {
			public void run() {
				playAudio();
			}
		}, "Beeper");
		playThd.start();
		
//		String label = "[" + sender + "@" + time + "]";
		
		StringBuffer strbuf_msg = null;
		if(strmsg != null){
			strbuf_msg = new StringBuffer(strmsg);
			int caretPos = -1;

			for (; (caretPos = strbuf_msg.indexOf("^n", caretPos + 1)) >= 0;) {
				// æŠŠ"^n"æ›¿æ�¢ä¸º"\n"
				strbuf_msg.replace(caretPos, caretPos + 2, "\n");
			}
		}
		chatHistory.appendMessage(sender, time, strmsg, incomingPic);
//		appendToHMsg(label, (strbuf_msg != null)?strbuf_msg.toString():null, incomingPic, true, false);
	}

	public void playAudio() {
		final AudioClip msgBeep;
		try {
			// AudioClip audioClip = Applet.newAudioClip(completeURL)
			// codeBase = new URL("file:" + System.getProperty("user.dir") +
			// "/");
			URL url = new URL("file:/" + System.getProperty("user.dir")
					+ System.getProperty("file.separator")
					+ SystemPath.AUDIO_RESOURCE_PATH
					+ "typewpcm.wav");
			msgBeep = Applet.newAudioClip(url);
			msgBeep.play();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}
	}
	
	public void playNudgeAudio() {
		final AudioClip msgBeep;
		try {
			// AudioClip audioClip = Applet.newAudioClip(completeURL)
			// codeBase = new URL("file:" + System.getProperty("user.dir") +
			// "/");
			URL url = new URL("file:/" + System.getProperty("user.dir")
					+ System.getProperty("file.separator")
					+ SystemPath.AUDIO_RESOURCE_PATH
					+ "nudgewpcm.wav");
			msgBeep = Applet.newAudioClip(url);
			msgBeep.play();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}
	}

/*	public void appendToHMsg(String label, String msg, ImageIcon incomingPic, boolean visible,
			boolean isFromMe) {
		StringBuffer label_buf = new StringBuffer(label);
		
		// System.out.println("label_buf :" + label_buf);
		// System.out.println("msg_buf :" + msg_buf);

		// playAudio();
		Style labelStyle = isFromMe ? green : blue;

		
		historymsg_save += (label_buf + "\n");

		if (msg != null && msg.equals(nudgeMsg)) {
			labelStyle = gray;

			DialogEarthquakeCenter dec = new DialogEarthquakeCenter(parent);
			dec.startNudging();
			tp_historymsg.setEditable(true);
			tp_historymsg.setCaretPosition(styledDoc.getLength());
			styledDoc.setLogicalStyle(tp_historymsg.getCaretPosition(),
					labelStyle);
			tp_historymsg.replaceSelection(label + '\n');
			tp_historymsg.setCaretPosition(styledDoc.getLength());// !!!
			styledDoc.setLogicalStyle(tp_historymsg.getCaretPosition(), italic);
			tp_historymsg
					.replaceSelection("YOU JUST RECEIVED A NUDGE MESSAGE\n");
			tp_historymsg.setEditable(false);
			return;
		}

		if (visible)
		{
			tp_historymsg.setEditable(true);

			
			tp_historymsg.setCaretPosition(styledDoc.getLength());
			styledDoc.setLogicalStyle(tp_historymsg.getCaretPosition(),
					labelStyle);
			tp_historymsg.replaceSelection(label + '\n');
			System.out.println("label :" + label);
			
			if(msg != null && !msg.equals("")){
				StringBuffer msg_buf = new StringBuffer(msg);
				historymsg_save += (msg_buf + "\n");
				
				System.out.println("msg :" + msg);
	
				tp_historymsg.setCaretPosition(styledDoc.getLength());// !!!
				styledDoc.setLogicalStyle(tp_historymsg.getCaretPosition(), bold);
				
				int position = 0, caretPos = 0;
	
				for (; (caretPos = msg_buf.indexOf("[F:", position)) >= 0;) {
					// System.out.println("caretPos : " + caretPos);
					// StringBuffer msgpiece = new
					// StringBuffer(msg_buf.substring(caretPos, caretPos + 6));
					// System.out.println("msgpiece : " + msgpiece);
	
					if (msg_buf.substring(caretPos, caretPos + 7).matches(
							"\\[F\\:[0-9][0-9][0-9]\\]")) {
						
						tp_historymsg.setCaretPosition(styledDoc.getLength());
						tp_historymsg.replaceSelection(msg_buf.substring(position,
								caretPos));
						
						tp_historymsg.setCaretPosition(styledDoc.getLength());
						int faceindex = Integer.parseInt(msg_buf.substring(
								caretPos + 3, caretPos + 6));
						tp_historymsg.insertIcon(getImageIconFace(faceindex));
						
						position = caretPos + 7;
					} else {
						tp_historymsg.setCaretPosition(styledDoc.getLength());
						tp_historymsg.replaceSelection(msg_buf.substring(position,
								caretPos + 3));
						// å�Žç§»position
						position = caretPos + 3;
					}
				}

				tp_historymsg.setCaretPosition(styledDoc.getLength());
				tp_historymsg.replaceSelection(msg_buf.substring(position) + '\n');
			}
			if(incomingPic != null){
				tp_historymsg.setCaretPosition(styledDoc.getLength());
				tp_historymsg.insertIcon(incomingPic);
				tp_historymsg.setCaretPosition(styledDoc.getLength());
				tp_historymsg.replaceSelection("\n");
			}
			// System.out.println("msg_buf.substring(position) :" +
			// msg_buf.substring(position));
			// *****************************************************
			tp_historymsg.setEditable(false);// é‡�æ–°è®¾ä¸ºä¸�å�¯ç¼–è¾‘
		}
		this.repaint();
	}*/
	
	@SuppressWarnings("unused")
	private void appendFaceToInputPane(ImageIcon selectedFace) {
		tp_input.setEditable(true);
		tp_input.insertIcon(selectedFace);
	}

	public String getHistoryMsgs() {
		// return tp_hmsg.getText();
		return historymsg_save;
	}


	private void sendMessage() {
		Thread sender = new Thread(new Runnable(){
			public void run() {
				//System.out.println("sendMessage(): >" + tp_input.getText() + "<");
				String msg = tp_input.getText();
				tp_input.setText("");
				
				if(msg.equals("")){
					System.out.println("You're trying to send a empty message, it's not suggested.");
					
					return;
				}
				Date date = new Date();
				// fmDate = new SimpleDateFormat("yyyy/MM/dd E HH:mm:ss");
//				String label = "I say@" + fmDate.format(date) + ":";

				chatHistory.appendMessage("me", fmDate.format(date), msg, null);
//				appendToHMsg(label, msg, null, true, true);
				
				StringBuffer strbuf_msg = new StringBuffer(msg);
				int caretPos = -1;

				for (; (caretPos = strbuf_msg.indexOf("\r\n", caretPos + 1)) >= 0;) {
					strbuf_msg.replace(caretPos, caretPos + 2, "^n");
				}
				System.out.println("strbuf_msg :" + strbuf_msg);

				/*boolean succeed = parent.SendMsg(new String(strbuf_msg));
				if(!succeed){
					//TODO tell user what happend.
					showFailedSendingMsg(new String(strbuf_msg));
				}*/
			}
		});
		sender.start();
	}

	public void actionPerformed(ActionEvent e) {
		JButton srcButton = (JButton) e.getSource();
		if (srcButton.getActionCommand().equals("Send")) {
			System.out.println("You clicked the button : Send");
			// insert(getText(), null);
			sendMessage();
		} else if (srcButton.getActionCommand().equals("Emotion")) {
			System.out.println("You clicked the button : InsertImage");

			/*int selectedfaceIndex = selFace.getSelectedFaceIndex();
			if (selectedfaceIndex != -1) {
				System.out.println("You selected the face : "
						+ selectedfaceIndex + ".gif");
				appendFaceToInputPane(selectedfaceIndex);
			}*/
			/*
			 * ImageIcon selectedface = getImageIconFace(selectedfaceIndex); if
			 * (selectedface != null) { System.out.println("You selected the
			 * face : " + selectedfaceIndex + ".gif");
			 * appendFaceToInputPane(selectedface); }
			 */
		}  else if (srcButton.getActionCommand().equals("SendPic")) {
			
		}  else if (srcButton.getActionCommand().equals("SendFile")) {
			
		} 
	}
}